<?php

// +---------------------------------------------+
// |     Copyright  2010 - 2018 InterPhoto       |
// |     http://www.weentech.com                 |
// |     This file may not be redistributed.     |
// +---------------------------------------------+


include('includes/InterPhoto.Core.php');

if($userinfo['userid']){
	header("Location: ".GetUrl('mydesk.upload.php'));
	exit();
}elseif(!$userinfo['allowupload']){
	header("Location: ".GetUrl('login.php'));
	exit();
}

header("Expires: Mon, 18 Jul 1988 01:08:08 GMT"); // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); // HTTP/1.0

$action = ForceIncomingString('action', 'uploadform');

$smarty = new InterPhoto;
$showform = 0;

@set_time_limit(900);

// ############################## FUNCTIONS #############################

function CreateDirectory($path) {
	if (!file_exists($path)) {
		mkdir($path, 0777);
		@chmod($path, 0777);
	}
}

function UploadImage($imagefile, $uploaddir, $file_path, $imagename) {
	CreateDirectory($uploaddir.$file_path);
	CreateDirectory($uploaddir.$file_path.'/32x32/');
	CreateDirectory($uploaddir.$file_path.'/80x80/');
	CreateDirectory($uploaddir.$file_path.'/160x160/');
	CreateDirectory($uploaddir.$file_path.'/760x760/');
	CreateDirectory($uploaddir.$file_path.'/original/');

	if((function_exists('move_uploaded_file') AND @move_uploaded_file($imagefile['tmp_name'], $uploaddir.$file_path.'/'.$imagename)) OR @rename($imagefile['tmp_name'], $uploaddir.$file_path.'/'.$imagename))	{

		$image_size = @getimagesize($uploaddir.$file_path.'/'.$imagename);
		if(!$image_size) return false;

		if ($image_size[0] > 760 || $image_size[1] > 760) {
			if (@rename($uploaddir.$file_path.'/'.$imagename, $uploaddir.$file_path.'/original/'.$imagename)) {
				CreateImageFile($uploaddir.$file_path.'/original/'.$imagename, $uploaddir.$file_path."/760x760/".$imagename,'760');
				CreateImageFile($uploaddir.$file_path.'/760x760/'.$imagename, $uploaddir.$file_path."/160x160/".$imagename,'160');
				CreateImageFile($uploaddir.$file_path.'/160x160/'.$imagename, $uploaddir.$file_path."/80x80/".$imagename,'80');
				CreateImageFile($uploaddir.$file_path.'/80x80/'.$imagename, $uploaddir.$file_path."/32x32/".$imagename,'32');
			}
		}else{
			if (@rename($uploaddir.$file_path.'/'.$imagename, $uploaddir.$file_path.'/760x760/'.$imagename)) {
				CreateImageFile($uploaddir.$file_path.'/760x760/'.$imagename, $uploaddir.$file_path."/160x160/".$imagename,'160');
				CreateImageFile($uploaddir.$file_path.'/160x160/'.$imagename, $uploaddir.$file_path."/80x80/".$imagename,'80');
				CreateImageFile($uploaddir.$file_path.'/80x80/'.$imagename, $uploaddir.$file_path."/32x32/".$imagename,'32');
			}
		}

		return true;

	}else{
		return false;
	}
}

function CreateImageFile($src_path, $des_path, $new_dims) {
	$source = @imagecreatefromjpeg($src_path);

	if ($source) {
		$imageX = @imagesx($source);
		$imageY = @imagesy($source);
		
		if ($imageX >= $imageY) {
			if($imageX >= $new_dims){
				$thumbX = $new_dims;
				$thumbY = (int)(($thumbX*$imageY) / $imageX );
			}else{
				$thumbX = $imageX;
				$thumbY = $imageY;
			}
		} else {
			if($imageY >= $new_dims){
				$thumbY = $new_dims;
				$thumbX = (int)(($thumbY*$imageX) / $imageY );
			}else{
				$thumbX = $imageX;
				$thumbY = $imageY;
			}
		}

		$dest_thum  = @imagecreatetruecolor($thumbX, $thumbY);
		@imagecopyresampled ($dest_thum, $source, 0, 0, 0, 0, $thumbX, $thumbY, $imageX, $imageY);
		@imageinterlace($dest_thum);
		@imagejpeg($dest_thum,$des_path,85);
		@ImageDestroy($dest_thum);
		@ImageDestroy($source);
	}
}

function GetCategorySelect($selectname, $selectedid = 0){
	$sReturn = '<select name="' . $selectname . '">';
	$sReturn .= GetOptions($selectedid);
	$sReturn .= '</select>';

	return $sReturn;
}

function GetOptions($selectedid = 0, $parentid = 0, $sublevelmarker = ''){
	global $icategories;

	if($parentid) $sublevelmarker .= '&minus;&minus;';

	$allicategories = $icategories;
	foreach($allicategories as $value){
		if($parentid == $value['parentid']){
			$sReturn .= '<option value="' . $value['categoryid'] . '" ' . Iif($selectedid == $value['categoryid'], 'SELECTED', '') . '>' . $sublevelmarker . $value['title'] . '</option>';

			$sReturn .= GetOptions($selectedid, $value['categoryid'], $sublevelmarker);
		}
	}

	return $sReturn;
}

// ############################## FUNCTIONS #############################


if($action == 'insertimage')
{
	$categoryid     = ForceIncomingInt('categoryid');
	$title        = ForceIncomingString('title');
	$description        = ForceIncomingString('description');
	$keywords        = ForceIncomingString('keywords');
	$url        = ForceIncomingString('url');
	$sale     = ForceIncomingInt('sale');
	$price        = ForceIncomingString('price');
	$vvckey           = ForceIncomingInt('vvckey');
	$vvc           = ForceIncomingString('vvc');

	if(strlen($title) == 0){
		$errors[] = $sys_langs['please_enter'].$langs['image'].$langs['title'];
	}

	if(!CheckVVC($vvckey, $vvc)){
		$errors[] = $sys_langs['badvvc'];
	}

	$imagefile         = $_FILES['imagefile'];

	$valid_image_types = array('image/pjpeg',	'image/jpeg', 'image/jpg');

	$uploaddir = BASEPATH.'MyWebsiteImages/';
	@chmod($uploaddir,0777);

	if (!$categoryid)
	{
		$errors[] = $sys_langs['nocategory'];
	}

	if (!function_exists('imagecreatetruecolor'))
	{
		$errors[] = $sys_langs['notsupportgd2'];
	}

	if (!is_dir($uploaddir)){
		$errors[] = $sys_langs['nodirectory'];
	}else if (!is_writable($uploaddir)){
		$errors[] = $sys_langs['notwritable'];
	}

	if($imagefile['size'] == 0)	{
		$errors[] = $sys_langs['errfilesize1'].ini_get('upload_max_filesize');
	}elseif (!IsUploadedFile($imagefile['tmp_name']) || !($imagefile['tmp_name'] != 'none' && $imagefile['tmp_name'] && $imagefile['name']) ){
		$errors[] ='Possible file upload attack!';
	}elseif(!in_array($imagefile['type'], $valid_image_types)){
		$errors[] = $sys_langs['invalidtype'];
	}else{
		$filesizelimit = $DB->query_first("SELECT title, datasize, watermark FROM " . TABLE_PREFIX . "categories WHERE categoryid = '$categoryid' ");
		if($imagefile['size'] > $filesizelimit['datasize'] *1024){
			$errors[] = str_replace('//1', $filesizelimit['title'], $sys_langs['errfilesize2']). DisplayFilesize($filesizelimit['datasize'] *1024);
		}else{
			$watermark = $filesizelimit['watermark'];
		}
	}

	if(!isset($errors))
	{
		$file_path_name = DisplayDate(time(), 'Y_m');
		$filepieces = explode('.', basename($imagefile['name']));
		$fileExtension = strtolower($filepieces[count($filepieces)-1]);
		$imagename = md5(uniqid(COOKIE_KEY.time())).'.'.$fileExtension;
		$file_path = $file_path_name.'_'.WEBSITE_KEY;

		if(UploadImage($imagefile, $uploaddir, $file_path, $imagename)){

			$DB->query("INSERT INTO " . TABLE_PREFIX . "images VALUES (NULL, 0,  '$categoryid', 0, '".Iif($langs['guest'], $langs['guest'], $userinfo['name'])."', '$userinfo[allowuploadshow]', '$watermark', '$sale', '0', 'all', '$file_path_name', '$imagename', '$price', '$title', '$description', '', '$keywords', '$url', '0', '0', '".time()."')");

			$thisimageid = $DB->insert_id();
			$DB->query("UPDATE " . TABLE_PREFIX . "images SET ordernum = '$thisimageid' WHERE imageid = '$thisimageid'");

			$successtitle = $sys_langs['thanksforpublish'];
			$success = Iif($userinfo['allowuploadshow'], $sys_langs['clickforview'].'<a href="'.GetUrl('InterPhoto.php', 'id', $thisimageid).'">'.GetUrl('InterPhoto.php', 'id', $thisimageid).'</a>', $sys_langs['needadmincheck']);

		}else{
			$errors = $sys_langs['uploadfailed'];
		}
	}
	  
	if(isset($errors))	{
		$errortitle = $langs['publish'].$langs['image'].$sys_langs['error'];
		$action = 'uploadform';
	}
}


if($action == 'uploadform')
{
	$getcategories = $DB->query("SELECT categoryid, parentid, title  FROM " . TABLE_PREFIX . "categories WHERE actived = 1 ORDER BY ordernum");
	$icategories = $DB->getrows($getcategories);

	if(isset($errors))
	{
		$image = array('categoryid'     => $categoryid,
			'title'     => $title,
			'description'     => $_POST['description'],
			'keywords'     => $keywords,
			'url'     => $url,
			'sale'     => $sale,
			'price'     => $price);

	}else{
		$image = array('imageid' => 0, 'categoryid' => 0);
	}

	$showform = 1;
	$Editor = '<script src="'.BASEURL.'library/editor/nicEdit.js" type="text/javascript"></script>
	<script type="text/javascript">
	bkLib.onDomLoaded(function() {
	new nicEditor({fullPanel:true, iconsPath: \''.BASEURL.'library/editor/nicEditorIcons.gif\', maxHeight:150}).panelInstance("description658");
	});
	</script>';
	$smarty->assign('Editor', $Editor);
	$smarty->assign('vvckey', CreateVVC());
	$smarty->assign('categoryselect', GetCategorySelect('categoryid', $image['categoryid']));
	$smarty->assign('image', $image);
}

$getimages = $DB->query("SELECT i.imageid, i.path, i.filename, i.title FROM " . TABLE_PREFIX . "images i LEFT JOIN  " . TABLE_PREFIX . "categories c ON (c.categoryid = i.categoryid) WHERE (i.usergroupids = 'all' OR i.usergroupids LIKE '%(".$userinfo['groupid'].")%') AND i.actived = 1 AND c.actived = 1 ORDER BY rand() LIMIT 10");

$images = $DB->getrows($getimages);

$smarty->assign('images', $images);
$smarty->assign('showform', $showform);

//Always needing
$pagenav = '<a href="'.GetUrl('index.php').'">'.$langs['home'].'</a> '.$langs['nav'].' <a href="'.GetUrl('publish.php').'">'.$langs['publish'].$langs['image'].'</a>';
$smarty->assign('pagenav', $pagenav);
$smarty->assign('userinfo', $userinfo);
$smarty->assign('pagetitle', $langs['publish'].$langs['image'] . ' - ' .$mainsettings['siteTitle']);

$smarty->interPlay('publish.tpl');

?>